package team.bluepen.order.web.servlet.user;

import team.bluepen.order.ErrorPack;
import team.bluepen.order.constant.Constant;
import team.bluepen.order.constant.ErrorCode;
import team.bluepen.order.data.database.mysql.UserRepository;
import team.bluepen.order.data.entity.Role;
import team.bluepen.order.data.entity.User;
import team.bluepen.order.util.Log;
import team.bluepen.order.util.StringUtil;
import team.bluepen.order.util.UserChecker;
import team.bluepen.order.web.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 创建用户。需要携带身份参数，不携带视为注册，默认USER身份
 * @author RollW
 */
@WebServlet(name = "UserCreateServlet",
        urlPatterns = {"/api/user/create", "/api/user/register"})
public class UserCreateServlet extends BaseServlet {
    public static final String USERNAME_PARAM = "username";
    public static final String PASSWORD_PARAM = "password";
    public static final String ROLE_PARAM = "role";

    @Override
    protected boolean isCheckLogin() {
        return false;
    }

    @Override
    protected void post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter(USERNAME_PARAM);
        String password = req.getParameter(PASSWORD_PARAM);
        String roleString = req.getParameter(ROLE_PARAM);
        setJsonHeader(resp);
        if (StringUtil.isEmpty(username)) {
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_PARAM_MISSING,
                    "Missing username.")
                    .toCodePack());
            return;
        }
        if (StringUtil.isEmpty(password)) {
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_PARAM_MISSING,
                    "Missing password.")
                    .toCodePack());
            return;
        }

        Role role = Role.get(roleString);
        if (role == null) {
            role = Role.USER;
        } else {
            User user = (User) req.getSession().getAttribute(Constant.SESSION_USER);
            if (user == null || user.getRole() != Role.ADMIN) {
                writeJson(resp, new ErrorPack(ErrorCode.ERROR_ILLEGAL_ACCESS,
                        "Non-administrator users are not allowed to set roles.")
                        .toCodePack());
                return;
            }
        }
        User newUser = new User()
                .setPassword(password)
                .setUsername(username)
                .setRole(role);
        ErrorCode checkCode = UserChecker.checkUser(newUser);
        if (!checkCode.getState()) {
            writeJson(resp, new ErrorPack(checkCode, checkCode.toString())
                    .toCodePack());
            return;
        }
        UserRepository repository = new UserRepository();
        ErrorCode createCode = repository.createUser(newUser);
        writeJson(resp, new ErrorPack(ErrorCode.SUCCESS, createCode.toString())
                .toCodePack());
        Log.i("User create success.");
    }
}
